/*
 * 软件版权: 恒生电子股份有限公司
 * 修改记录:
 * 修改日期     修改人员  修改说明
 * ========    =======  ============================================
 * 2021/4/1  lisy31662  新增
 * ========    =======  ============================================
 */
package com.sansi.pencilbook.util;

import org.thymeleaf.expression.Lists;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 功能说明:
 *
 * @author lisy31662
 */
public class FileUtil {

  /**
   * 获取下载的字节
   * @param filePath
   * @return
   * @throws Exception
   */
  public static String gainDwnString(String filePath) throws Exception {
    String result = "";
    List<File> fileList = getListFiles(filePath);
    if (fileList == null) {
      return null;
    }
    FileInputStream inputstream = null;
    if (fileList.size()==1) {
      inputstream = new FileInputStream(fileList.get(0));
    }else {
      throw new Exception("发现了多个文件");
    }
    if (inputstream == null) {
      return null;
    }
    byte[] bytes = new byte[inputstream.available()];
    inputstream.read(bytes);
    return new String(bytes, StandardCharsets.UTF_8);
  }

  /**
   * 获取下载的字节
   * @param filePath
   * @return
   * @throws Exception
   */
  public static byte[] gainDwnBytes(String filePath) throws Exception {
    String result = "";
    List<File> fileList = getListFiles(filePath);
    if (fileList == null) {
      return new byte[0];
    }
    FileInputStream inputstream = null;
    if (fileList.size()==1) {
      inputstream = new FileInputStream(fileList.get(0));
    }else {
      throw new Exception("发现了多个文件");
    }
    if (inputstream == null) {
      return new byte[0];
    }
    byte[] bytes = new byte[inputstream.available()];
    inputstream.read(bytes);
    return bytes;
  }

  /**
   * 获取文件列表
   * @param path
   * @return
   */
  public static List<File> getListFiles(String path) {
    File file = new File(path);
    if (file == null)
      return null;
    if (file.isFile()) {
      List<File> list = new ArrayList<>();
      list.add(file);
      return list;
    }
    File[] files = file.listFiles();
    if (files == null && file.isDirectory())
      return null;
    return Arrays.asList(files);
  }

}
